package top.ruanlitao.shortlink.admin.common.biz.user;

import cn.hutool.core.util.StrUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import top.ruanlitao.shortlink.admin.common.constant.UserConstant;

import java.io.IOException;

/**
 * 用户上下文信息传输过滤器
 */
@RequiredArgsConstructor
public class UserTransmitFilter implements Filter {

    /**
     * 通过网关鉴权后才能到达这里，在这里只需要将当前登录的用户信息保存在 ThreadLocal 中即可
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        // 获取请求头中各个用户信息字段
        String username = httpServletRequest.getHeader(UserConstant.KEY_USERNAME);
        String userId = httpServletRequest.getHeader(UserConstant.KEY_USER_ID);
        String realName = httpServletRequest.getHeader(UserConstant.KEY_REAL_NAME);
        if (StrUtil.isAllNotBlank(username, userId, realName)) {
            UserInfoDTO userInfoDTO = new UserInfoDTO(userId, username, realName);
            UserContext.setUser(userInfoDTO);
        }
        try {
            // 过滤器放行
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            UserContext.removeUser();
        }

    }
}
